<template>
  <div class="user-list">
    <!-- 查询区域 -->
    <el-card class="mb">
      <el-form :model="searchParams" inline>
        <el-form-item label="用户ID">
          <el-input
            v-model="searchParams.userId"
            placeholder="请输入用户ID"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="用户编号">
          <el-input
            v-model="searchParams.userNo"
            placeholder="请输入用户编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input
            v-model="searchParams.nickname"
            placeholder="请输入用户昵称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table
        :data="dataList"
        v-loading="loading"
        style="width: 100%"
        :fit="true"
      >
        <el-table-column
          prop="id"
          label="用户ID"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="userNo" label="用户编号" min-width="120" />
        <el-table-column
          prop="nickname"
          label="昵称"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column label="头像" width="100" align="center">
          <template #default="{ row }">
            <el-avatar
              :src="row.avatar"
              :size="50"
              @click="handlePreviewImage(row.avatar, row.nickname)"
              style="cursor: pointer"
            />
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.gender === 0" type="info">男</el-tag>
            <el-tag v-else-if="row.gender === 1" type="danger">女</el-tag>
            <el-tag v-else type="warning">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="birth" label="生日" width="120" align="center" />
        <el-table-column
          prop="countryCode"
          label="国家"
          width="100"
          align="center"
        />
        <el-table-column
          prop="appLanguage"
          label="语言"
          width="100"
          align="center"
        />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.status === 0" type="success">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="deviceNo"
          label="设备号"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="200"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="danger" size="small" @click="handleBlock(row)">
                <el-icon><Lock /></el-icon>
                封禁
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleBlockAvatar(row)"
              >
                <el-icon><Lock /></el-icon>
                重置头像
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        class="pagination-center mt mb"
        v-model:current-page="pageInfo.page"
        v-model:page-size="pageInfo.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="sizes, prev, pager, next, jumper,total"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </el-card>

    <!-- 图片预览组件 -->
    <ImagePreview
      v-model="previewVisible"
      :image-url="previewImageUrl"
      :title="previewTitle"
    />

    <!-- 添加封禁弹窗 -->
    <el-dialog
      v-model="blockDialogVisible"
      title="添加封禁"
      width="600px"
      :close-on-click-modal="false"
      @close="handleCancelBlock"
    >
      <el-form
        ref="blockFormRef"
        :model="blockForm"
        :rules="blockRules"
        label-width="120px"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model="blockForm.userId"
            placeholder="请输入用户ID"
            clearable
            disabled
          />
        </el-form-item>

        <el-form-item label="用户昵称">
          <el-input v-model="currentUser.nickname" disabled />
        </el-form-item>

        <el-form-item label="封禁类型" prop="type">
          <el-select
            v-model="blockForm.type"
            placeholder="请选择封禁类型"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="(text, value) in blockTypes"
              :key="value"
              :label="text"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="封禁内容" prop="content">
          <el-input
            v-model="blockForm.content"
            placeholder="系统根据封禁类型自动填充"
            clearable
            disabled
          />
          <div v-if="blockForm.type === 1" class="form-tip">
            <el-tag type="info" size="small">账号封禁时自动填充用户ID</el-tag>
          </div>
          <div v-if="blockForm.type === 2" class="form-tip">
            <el-tag type="info" size="small">设备封禁时自动填充设备号</el-tag>
          </div>
          <div v-if="blockForm.type === 3" class="form-tip">
            <el-tag type="info" size="small">IP封禁时自动填充 0.0.0.0</el-tag>
          </div>
          <div v-if="blockForm.type === 4" class="form-tip">
            <el-tag type="info" size="small">房间封禁时自动填充用户编号</el-tag>
          </div>
        </el-form-item>

        <el-form-item label="封禁原因" prop="reasonCategory">
          <el-select
            v-model="blockForm.reasonCategory"
            placeholder="请选择封禁原因"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="(item, key) in blockCategories"
              :key="key"
              :label="item.zh"
              :value="key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="封禁时长" prop="durationOfSeconds">
          <el-select
            v-model="blockForm.durationOfSeconds"
            placeholder="请选择封禁时长"
            style="width: 100%"
          >
            <el-option label="永久封禁" :value="-1" />
            <el-option label="1小时" :value="3600" />
            <el-option label="6小时" :value="21600" />
            <el-option label="1天" :value="86400" />
            <el-option label="3天" :value="259200" />
            <el-option label="7天" :value="604800" />
            <el-option label="30天" :value="2592000" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="blockForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelBlock">取消</el-button>
          <el-button
            type="primary"
            :loading="blockLoading"
            @click="handleConfirmBlock"
          >
            确认封禁
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { useHttp } from "@/hooks/useHttp";
import { type UserInfo } from "@/api/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { Lock } from "@element-plus/icons-vue";
import ImagePreview from "@/components/ImagePreview.vue";
import {
  getBlockTypesApi,
  getBlockCategoriesApi,
  addBlockApi,
  BlockTypesRes,
  BlockCategoriesRes,
  BlockAddReq,
  resetUserAvatarApi,
} from "@/api/block";

// 查询参数
interface SearchType {
  userId: string;
  userNo: string;
  nickname: string;
}

const searchParams = ref<SearchType>({
  userId: "",
  userNo: "",
  nickname: "",
});

// 图片预览相关
const previewVisible = ref(false);
const previewImageUrl = ref("");
const previewTitle = ref("");

// 封禁相关
const blockDialogVisible = ref(false);
const blockLoading = ref(false);
const blockFormRef = ref();
const blockTypes = ref<BlockTypesRes>({});
const blockCategories = ref<BlockCategoriesRes>({});
const currentUser = ref<UserInfo>({} as UserInfo);

const blockForm = reactive<BlockAddReq>({
  userId: "",
  content: "",
  type: undefined,
  reasonCategory: "",
  remark: "",
  durationOfSeconds: 3600, // 默认1小时
});

// 封禁表单验证规则
const blockRules = {
  type: [{ required: true, message: "请选择封禁类型", trigger: "change" }],
  content: [
    {
      validator: (rule: any, value: any, callback: any) => {
        // 如果是IP封禁，不需要填写封禁内容
        if (blockForm.type === 3) {
          callback();
        } else if (blockForm.type === 1 || blockForm.type === 2) {
          // 账号封禁和设备封禁会自动填充内容，不需要验证
          callback();
        } else if (!value || value.trim() === "") {
          callback(new Error("请输入封禁内容"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  reasonCategory: [
    { required: true, message: "请选择封禁原因", trigger: "change" },
  ],
  durationOfSeconds: [
    { required: true, message: "请选择封禁时长", trigger: "change" },
  ],
};

// 使用封装的 useHttp hook，配置自定义参数名
const {
  dataList,
  loading,
  totals,
  pageInfo,
  loadData,
  handleSizeChange,
  handleCurrentChange,
  resetPagination,
} = useHttp<UserInfo>("/user/page", searchParams, {
  pageKey: "pageNum", // 使用 pageNum 而不是 page
  pageSizeKey: "pageSize", // 使用 pageSize
  totalKey: "total", // 使用 total
  listKey: "list", // 使用 list
});

// 查询方法
const handleSearch = () => {
  resetPagination();
  // resetPagination() 内部已经调用了 loadData()，不需要重复调用
};

// 重置方法
const handleReset = () => {
  searchParams.value = {
    userId: "",
    userNo: "",
    nickname: "",
  };
  resetPagination();
  // resetPagination() 内部已经调用了 loadData()，不需要重复调用
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 预览图片
const handlePreviewImage = (imageUrl: string, nickname: string) => {
  previewImageUrl.value = imageUrl;
  previewTitle.value = `${nickname} 的头像`;
  previewVisible.value = true;
};

// 封禁用户
const handleBlock = (row: UserInfo) => {
  currentUser.value = row;
  blockForm.userId = row.id;
  blockDialogVisible.value = true;
};

// 封禁用户
const handleBlockAvatar = async (row: UserInfo) => {
  try {
    // 显示确认弹窗
    await ElMessageBox.confirm("确定要重置该用户的头像吗？", "重置头像确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 用户点击确认后执行重置头像操作
    const res = await resetUserAvatarApi(row.id);

    console.log(res, "------------------------------------");
    if (res?.code === 200) {
      ElMessage.success("重置成功");
      loadData();
    } else {
      ElMessage.error("重置失败");
    }
  } catch (error) {
    // 用户取消操作或发生错误时不执行重置
    if (error === "cancel") {
      ElMessage.info("已取消重置");
    } else {
      ElMessage.error("重置失败，请重试");
    }
  }
};

// 监听封禁类型变化
watch(
  () => blockForm.type,
  (newType) => {
    if (newType === 1) {
      // 账号封禁：自动填充用户ID
      blockForm.content = currentUser.value.id || "";
    } else if (newType === 2) {
      // 设备封禁：自动填充设备号
      blockForm.content = currentUser.value.deviceNo || "";
    } else if (newType === 3) {
      // IP封禁：设置为 0.0.0.0
      blockForm.content = "0.0.0.0";
    } else if (newType === 4) {
      // IP封禁：设置为 0.0.0.0
      blockForm.content = currentUser.value.userNo || "";
    } else {
      // 其他类型：清空封禁内容
      blockForm.content = "";
    }
  }
);

// 确认封禁
const handleConfirmBlock = async () => {
  if (!blockFormRef.value) return;

  try {
    await blockFormRef.value.validate();
    blockLoading.value = true;

    // 根据封禁类型处理封禁内容
    let content = blockForm.content;
    if (blockForm.type === 1) {
      // 账号封禁：使用用户ID
      content = currentUser.value.id || "";
    } else if (blockForm.type === 2) {
      // 设备封禁：使用设备号
      content = currentUser.value.deviceNo || "";
    } else if (blockForm.type === 3) {
      // IP封禁：使用 0.0.0.0
      content = "0.0.0.0";
    }

    const requestData = {
      ...blockForm,
      content: content,
    };

    await addBlockApi(requestData);
    ElMessage.success("封禁成功");
    blockDialogVisible.value = false;

    // 刷新列表
    loadData();
  } catch (error) {
    console.error("封禁失败:", error);
    ElMessage.error("封禁失败");
  } finally {
    blockLoading.value = false;
  }
};

// 取消封禁
const handleCancelBlock = () => {
  blockDialogVisible.value = false;
  // 重置表单
  Object.assign(blockForm, {
    userId: "",
    content: "",
    type: undefined,
    reasonCategory: "",
    remark: "",
    durationOfSeconds: 3600,
  });
  // 清空当前用户信息
  currentUser.value = {} as UserInfo;
};

// 加载封禁类型
const loadBlockTypes = async () => {
  try {
    const response = await getBlockTypesApi();
    blockTypes.value = response.data;
  } catch (error) {
    console.error("加载封禁类型失败:", error);
    ElMessage.error("加载封禁类型失败");
  }
};

// 加载封禁原因分类
const loadBlockCategories = async () => {
  try {
    const response = await getBlockCategoriesApi();
    blockCategories.value = response.data;
  } catch (error) {
    console.error("加载封禁原因分类失败:", error);
    ElMessage.error("加载封禁原因分类失败");
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadData(); // 加载用户列表数据
  loadBlockTypes();
  loadBlockCategories();
});
</script>

<style lang="less" scoped>
.user-list {
  .mb {
    margin-bottom: 20px;
  }

  .fr {
    float: right;
  }

  .mt {
    margin-top: 20px;
  }

  .pagination-center {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;

    .el-button {
      margin: 0;
      flex-shrink: 0;
    }
  }

  .duration-tips {
    margin-top: 8px;
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .dialog-footer {
    text-align: right;
  }

  .form-tip {
    margin-top: 8px;
  }
}
</style>
